<template>
  <el-dialog
    v-model="dialogVisible"
    title="事项办理"
    top="4%"
    width="75%"
    :before-close="close"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
  >
    <div>
      <el-tabs v-model="tabName" @tab-change="handleTabChange">
        <el-tab-pane label="事项信息" name="matterInfo" />
      </el-tabs>
      <!--      <div class="absolute top-[70px] right-[25px] text-blue-500">-->
      <!--        【部门办理流程】- 事项办理-->
      <!--      </div>-->
    </div>
    <el-scrollbar max-height="61vh" v-loading="loading">
      <div class="mr-4">
        <template v-if="tabName === 'matterInfo'">
          <MatterInfo ref="matterInfo" :show-deadline-table="false" />
          <el-form label-width="85px">
            <el-form-item label="办理期限">
              <Table :data="tableData" :select-column="false">
                <TableColumn label="期限" :width="150">
                  <template #default="{ row }">
                    {{ formatDateStr(row.deadlineDate, 'YYYY年MM月DD日') }}
                  </template>
                </TableColumn>
                <TableColumn label="关键期限" :min-width="40">
                  <template #default="{ row }">
                    <KeyShow :status="row.isKey" />
                  </template>
                </TableColumn>
                <TableColumn label="办理状态" :width="100">
                  <template #default="{ row }">
                    <MatterHandleShow :status="row.feedbackStatus" />
                  </template>
                </TableColumn>
                <TableColumn
                  label="期限要求"
                  prop="deadlineRequire"
                  width="auto"
                  align="left"
                  header-align="left"
                />

                <TableColumn label="操作" :width="180">
                  <template #default="{ row, $index }">
                    <el-button
                      type="success"
                      size="small"
                      :disabled="disabledButton(row, $index)"
                      @click="addProcessDialog.show(row)"
                    >
                      反馈
                    </el-button>
                    <el-button
                      type="warning"
                      size="small"
                      :disabled="disabledDelayButton(row)"
                      @click="
                        delayAdd.show({
                          matterId: row?.matterId,
                          deadlineId: row?.id,
                          oldDeadline: row?.deadlineDate,
                        })
                      "
                    >
                      延期申请
                    </el-button>
                  </template>
                </TableColumn>
              </Table>
            </el-form-item>
          </el-form>
        </template>
      </div>
    </el-scrollbar>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">
          {{ isHandle ? '取消' : '关闭' }}
        </el-button>
        <el-button
          v-if="!disabledCoordinationButton()"
          type="primary"
          @click="coordinationAdd.show(rowData.matterId)"
        >
          协调申请
        </el-button>
      </div>
    </template>
    <AddProcessDialog ref="addProcessDialog" @update="update" />
    <CoordinationAdd ref="coordinationAdd" />
    <DelayAdd ref="delayAdd" />
  </el-dialog>
</template>
<script setup lang="ts">
import { computed, nextTick, reactive, ref, useTemplateRef } from 'vue'
import MatterInfo from '@/components/showInfo/MatterInfo.vue'
import Table from '@/components/table/Table.vue'
import TableColumn from '@/components/table/TableColumn.vue'
import {
  getMatterDetail,
  getMatterFeedbackDeadlinesByMatterId,
} from '@/api/mission/thing'
import AddProcessDialog from '@/views/mission/process/AddProcessDialog.vue'
import CoordinationAdd from '@/views/application/coordination/CoordinationAdd.vue'
import DelayAdd from '@/views/application/delay/DelayAdd.vue'
import MatterHandleShow from '@/components/statusShow/matterHandle/MatterHandleShow.vue'
import {
  EMatterHandleStatus,
  EMatterStatus,
} from '@/components/statusShow/util'
import { formatDateStr } from '@/plugins/date'
import KeyShow from '@/components/statusShow/key/KeyShow.vue'
import useUserStore from '@/stores/user'

const userStore = useUserStore()

// 协调申请
const coordinationAdd =
  useTemplateRef<typeof CoordinationAdd>('coordinationAdd')
// 延期申请
const delayAdd = useTemplateRef<typeof DelayAdd>('delayAdd')

const emit = defineEmits(['update'])
const matterInfo = useTemplateRef<InstanceType<typeof MatterInfo>>('matterInfo')
const addProcessDialog =
  useTemplateRef<InstanceType<typeof AddProcessDialog>>('addProcessDialog')

const dialogVisible = ref(false)
const loading = ref(false)
const tabName = ref('matterInfo')
const tableData = ref([])
const rowData = reactive({
  matterId: null,
  id: null,
  receiveState: null,
  leadUnitId: 0,
})

const isHandle = computed(() => {
  return (
    rowData.receiveState === EMatterStatus['已超时'] ||
    rowData.receiveState === EMatterStatus['正常推进']
  )
})

const isLeadUnit = computed(() => {
  return rowData.leadUnitId === userStore.unitId
})

function disabledDelayButton(row: any) {
  // 如果没有处于办理中状态，则禁用
  if (!isHandle.value) {
    return true
  }
  // 如果不是牵头单位，则禁用
  if (!isLeadUnit.value) {
    return true
  }
  // 如果不是未办理状态，则禁用
  return ![
    EMatterHandleStatus['未办理'],
    EMatterHandleStatus['不通过'],
  ].includes(row?.feedbackStatus)
}

function disabledButton(row: any, $index: number): boolean {
  // 如果数据不存在，或者不处于待办理状态，则禁用按钮
  if (
    !row ||
    ![EMatterHandleStatus['未办理'], EMatterHandleStatus['不通过']].includes(
      row.feedbackStatus,
    )
  ) {
    return true
  }

  // 如果当前行不第一个，则允许填写
  if ($index === 0) {
    return false
    // 如果当前行不是第一个，则判断上一个行是否处于已办理状态
  } else
    return (
      tableData.value[$index - 1]?.feedbackStatus !==
      EMatterHandleStatus['已办理']
    )
}

function disabledCoordinationButton() {
  // 如果不是牵头单位，则禁用
  if (!isLeadUnit.value) {
    return true
  }
  // 如果事项状态为已完成，则禁用
  return rowData.receiveState === EMatterStatus['已完成']
}

defineExpose({ show })

async function update() {
  await setMatterData()
  await getDeadLineList()
}

function show(row: any) {
  dialogVisible.value = true
  tabName.value = 'matterInfo'
  nextTick(async () => {
    Object.assign(rowData, {
      matterId: row.matterId,
      id: row.id,
    })
    loading.value = true
    await setMatterData()
    await getDeadLineList()
    loading.value = false
  })
}

async function setMatterData() {
  const { data } = await getMatterDetail(rowData.matterId)
  if (data.status === 200) {
    rowData.leadUnitId = data.data.leadUnitId
    rowData.receiveState = data.data.matterStatus
    await matterInfo.value.setData(data.data)
  }
}

async function getDeadLineList() {
  const { data } = await getMatterFeedbackDeadlinesByMatterId(rowData.matterId)
  if (data.status === 200) {
    tableData.value = data.data
  }
}

async function handleTabChange() {
  if (tabName.value === 'matterInfo') {
    await setMatterData()
  }
}

function close() {
  dialogVisible.value = false
  loading.value = false
  tableData.value = []
  Object.assign(rowData, {
    matterId: null,
    id: null,
    receiveState: null,
    leadUnitId: 0,
  })
  if (tabName.value === 'matterInfo') {
    matterInfo.value.reset()
  }
  tabName.value = 'matterInfo'
  emit('update')
}
</script>

<style scoped lang="scss">
:deep(.el-step__description) {
  white-space: pre-wrap;
}
</style>
